package com.rr.util;

import lombok.extern.slf4j.Slf4j;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryUsage;
import java.lang.management.ThreadInfo;

/**
 * 打印
 *
 * @author <a href="mailto:xilanxiao@skieer.com">xilanxiao</a>
 */
@Slf4j
public class MemoryUsageUtils {

    /**
     * 打印线程信息
     */
    public static void printThreadInfo() {
        long threadId = Thread.currentThread()
            .getId();
        ThreadInfo threadInfo = ManagementFactory.getThreadMXBean()
            .getThreadInfo(threadId);
        String threadName = threadInfo.getThreadName();
        MemoryUsage heapMemoryUsage = ManagementFactory.getMemoryMXBean()
            .getHeapMemoryUsage();
        long used = calc(heapMemoryUsage.getUsed());
        long max = calc(heapMemoryUsage.getMax());
        if (log.isInfoEnabled()) {
            log.info("Info threadId:{},threadName:{},memoryUsed:{},memoryMax:{}", threadId, threadName, used, max);
        }
    }

    /**
     * 字节数换算成M
     *
     * @param l 字节数
     * @return 兆字节
     */
    private static long calc(long l) {
        return l / 1024 / 1024;
    }

}
